package com.zhp.farmerclient.service;

import com.zhp.farmerclient.common.Result;
import com.zhp.farmerclient.entity.FileVO;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileService {

    @Value("${file.upload.path}")
    private String uploadPath;

    public FileVO upload(MultipartFile file) throws IOException {
        // 获取上传文件的原始文件名
        String fileName = file.getOriginalFilename();

        String destPath = uploadPath + File.separator + fileName;
        // 创建目标文件
        File destFile = new File(destPath);
        file.transferTo(destFile);
        return new FileVO(destPath,fileName);
    }

    public void download(String filePath, HttpServletResponse response) {
        try {
            //下载文件的路径
            String downPath = uploadPath +filePath;
            //读取目标文件
            File f = new File(downPath);
            // 获取文件后缀名
            String ext = filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase();
            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(f);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filePath, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + f.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public Result remove(String filename) {
        File file = new File(uploadPath+filename);
        System.out.println("delete+"+filename);
        if(file.exists()){
            file.delete();
            return Result.succ();
        }
        return Result.fail("删除失败");
    }
}
